# #	This script used to Control wireless adapter disconnect.
#Usage: WirelessConnect.py [options]
#
#Options:
#  -h, --help            show this help message and exit
#  -i INTERFACE, --interface=INTERFACE
#                        Be controlled wireless interface
#
#	Output:	0:	Success
#			1:	Failure
#			2:	Error
#
#	Check input parameter right
#	Disconnect wirless interface


import sys
import os
import subprocess
from optparse import OptionParser 
import CommentProcedure
import Configure



def checkSecurityValiable( AUTH, ENCRY, PASSPHRASE=None, WEPINDEX=None ):
	if not AUTH.lower() in [ 'open', 'shared', 'wpapsk', 'wpa2psk', 'wpa', 'wpa2']:
		return 'The argument about authentication not valiable. Use "-h" option to get detail information!'
	
	if not ENCRY.lower() in [ 'none', 'wep', 'tkip', 'aes']:
		return 'The argument about encryption not valiable. Use "-h" option to get detail information!'
	
	if AUTH.lower() in ['wpa','wpa2']:
		return 'This script not support wpa and wpa2 authentication for 802.1X now!\nFor 802.11 personal, please use "WPSPSK" or "WPS2PSK".'
	
	if AUTH.lower()=='open' and not ENCRY.lower() in ['none', 'wep']:
		return 'The argument about authentication and encryption not match!'
	
	if AUTH.lower()=='shared' and not ENCRY.lower() in ['wep']:
		return 'The argument about authentication and encryption not match!'
	
	if AUTH.lower()=='wpspsk' and not ENCRY.lower() in ['tkip','aes']:
		return 'The argument about authentication and encryption not match!'
	
	if AUTH.lower()=='wps2psk' and not ENCRY.lower() in ['tkip','aes']:
		return 'The argument about authentication and encryption not match!'	
	
	if ENCRY.lower()=='wep':
		if PASSPHRASE is None:
			return 'WEP key is neccessary for current security mode.'
		
		if not WEPINDEX in [1,2,3,4]:
			return 'The argument about WEP Index is wrong. Use "-h" option to get detail information!'
		
		if len( PASSPHRASE )!=5 and len( PASSPHRASE )!=10 and len( PASSPHRASE )!=13 and len( PASSPHRASE )!=26:
			return 'The argument about key length in WEP encryption is wrong. \nWEP key of 5 or 13 ANSI characters, or of 10 or 26 hexadecimal characters'
		
		import re
		p=re.compile( r'[^A-Fa-f0-9]' )
		
		if len( PASSPHRASE ) in [10,26] and len( p.findall( PASSPHRASE ) )!=0:
			return 'The argument about key in WEP encryption is wrong. \nWEP key of 10 or 26 hexadecimal characters'
			
	if AUTH.lower() in ['wpapsk','wpa2psk']:
		if PASSPHRASE is None:
			return 'Passphrase is neccessary for current security mode'
		
		if len( PASSPHRASE ) < int(8) or len( PASSPHRASE ) > int(64):
			return 'The argument about passphrase length is wrong, The valiable length is 8~64.'
		
		import re
		p=re.compile(r'[^A-Fa-f0-9]')	
		
		if len( PASSPHRASE )==64 and len(p.findall( PASSPHRASE ))!=0:
			return 'The argument about passphrase is wrong, a key of 64 hexadecimal characters.'				
	#Every thing is fine, return 0
	return int(0)
	
def checkArgumentValiable( options ):
	if options.interface is None:
		return 'Be controlled wireless interface is neccessary.\nInput wireless interface with option "-i" or "--interface".'
	return 0
	
def retrieveWirelessInterfaces():
	global tempfilepath
	process_response = os.system( 'netsh wlan show interface >> %s'%tempfilepath )
#	tempfile = file( tempfilepath,'w' )
#	process_response = subprocess.call('netsh wlan show interface', stdout=tempfile, stderr=subprocess.STDOUT, shell=True)
#	tempfile.flush()
#	tempfile.close()
	tempfile = file( tempfilepath,'r' )
	templist = []
	tempdirc = {}
	flag = 1
	while flag:
		temp = tempfile.readline()
		if temp == '':
			flag = 0
#			print 1
			break
		if temp.find( Configure.SYS_NETSH_SHOW_WLAN_INTERFACE_NAME ) != -1:
			temp=temp.strip('\n')
			tempdirc = {}
			tempdirc[temp.split(':')[0].strip()] = temp.split(':')[1].strip()
#			print 3
			continue
		if temp.find( Configure.SYS_NETSH_SHOW_WLAN_INTERFACE_HOST ) != -1:
			temp=temp.strip('\n')
			templist.append(tempdirc)
#			print 4
			continue
		if temp.find( ':' ) !=-1:
			temp=temp.strip('\n')
			tempdirc[temp.split(':')[0].strip()] = temp.split(':')[1].strip()
#			print 5
			continue			
	tempfile.close()
	CommentProcedure.deleteFiles( tempfilepath )
	return templist
	
def disconnectWireless(	INTERFACE ):
	global tempfilepath
	process_response = os.system( 'netsh wlan disconnect interface=%s >> %s'%(INTERFACE, tempfilepath) )	
#	tempfile = file( tempfilepath,'w' )
#	process_response = subprocess.call('netsh wlan disconnect interface=%s'%(INTERFACE), stdout=tempfile, stderr=subprocess.STDOUT, shell=True)
#	tempfile.flush()
#	tempfile.close()
	tempfile = file( tempfilepath,'r' )
	temp = tempfile.read()
	if temp.find ( Configure.SYS_NETSH_DISCONN_WLAN_CONFIRM_OK ) != -1:
		tempfile.close()
		CommentProcedure.deleteFiles( tempfilepath )
		return 0
	else:
		tempfile.close()
		CommentProcedure.deleteFiles( tempfilepath )
		return 1	
	
def checkWirelessState( INTERFACE_LIST, INTERFACE ):
	state = ''
	for temp in INTERFACE_LIST:
		if temp[Configure.SYS_NETSH_SHOW_WLAN_INTERFACE_NAME] == INTERFACE:
			state = temp["State"]
	return state			
	
def checkInterfaceExisted( INTERFACE_LIST, INTERFACE ):
	for interfaceinfo in INTERFACE_LIST:
		if interfaceinfo[Configure.SYS_NETSH_SHOW_WLAN_INTERFACE_NAME] == INTERFACE:
			return 0
	return 1
	
def main():
	global tempfilepath
	parser = OptionParser()  
	parser.add_option('-i', '--interface', dest='interface', help='Be controlled wireless interface')	
	(options, args) = parser.parse_args()
#	Initial 		
	this_path = os.path.dirname(sys.argv[0]) + r'/'
	logFile = os.path.abspath( this_path + Configure.logFile )
	errorFile = os.path.abspath( this_path + Configure.errorFile )
	proFile = os.path.abspath( this_path + Configure.proFile )
	newFile = os.path.dirname( proFile ) + r'\newprofile.xml'
	tempfilepath = os.path.abspath( this_path + r'WirelessDisconnect_temp.log' )
#	Check the inputed argument is valiable.
#	print 'debug: %s'%options	
	response = checkArgumentValiable( options )
	if response != 0:
		print response
		sys.exit(2)
		
	if checkInterfaceExisted( retrieveWirelessInterfaces(), options.interface ) != 0:
		print 'The argument about interface not existed'
		sys.exit(2)		
	try:
#	Disconnect wireless connection
		wireless_state = checkWirelessState( retrieveWirelessInterfaces(), options.interface )
		if 	wireless_state == '':
			print 'Interface %s still not existed'%( options.interface )
			sys.exit(1)
		if wireless_state == Configure.SYS_NETSH_SHOW_WLAN_INTERACE_STATE_CONNECT:
			if disconnectWireless( options.interface ):
				print 'Initial try to disconnect interface %s fail!'%( options.interface )
				sys.exit(1)
		print 'Success'
		sys.exit(0)
	except Exception, e:
		print 'Wireless interface disconnect have error:\n%s'%e
		sys.exit(2)

if __name__ == "__main__":
	main()
	
 	